<template>
  <view class="order-detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="error-container">
      <view class="error-icon">!</view>
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="fetchOrderDetail">重新加载</button>
    </view>

    <!-- 订单详情内容 -->
    <view v-else-if="orderDetail" class="order-content">
      <!-- 订单状态卡片 -->
      <view class="status-card">
        <view class="status-icon" :class="getStatusIconClass(orderDetail.status)">
          <text class="icon-text">{{ getStatusIcon(orderDetail.status) }}</text>
        </view>
        <view class="status-info">
          <text class="status-text">{{ formatStatus(orderDetail.status) }}</text>
          <text class="status-desc">{{ getStatusDesc(orderDetail.status) }}</text>
        </view>
      </view>

      <!-- 景点门票信息 -->
      <view class="section tickets-section">
        <view class="section-title">
          <text class="title-text">门票信息</text>
        </view>
        <view v-if="orderDetail.orderTickets && orderDetail.orderTickets.length > 0" class="tickets-list">
          <view 
            v-for="orderTicket in orderDetail.orderTickets" 
            :key="orderTicket.orderTicketId" 
            class="ticket-card"
          >
            <!-- 景点图片 -->
            <view class="ticket-image-wrapper">
              <image 
                :src="getSightImage(orderTicket.ticket?.sight)" 
                mode="aspectFill" 
                class="ticket-image"
              ></image>
            </view>
            
            <!-- 门票详情 -->
            <view class="ticket-info">
              <text class="sight-name">{{ orderTicket.ticket?.sight?.name || '未知景点' }}</text>
              <text class="ticket-type">{{ getTicketTypeName(orderTicket.ticket?.ticketType) }}</text>
              
              <!-- 景点地址 -->
              <view v-if="orderTicket.ticket?.sight?.address" class="sight-address">
                <uni-icons type="location" size="14" color="#999"></uni-icons>
                <text class="address-text">{{ orderTicket.ticket.sight.address }}</text>
              </view>
              
              <!-- 开放时间 -->
              <view v-if="orderTicket.ticket?.sight?.openTime" class="open-time">
                <uni-icons type="clock" size="14" color="#999"></uni-icons>
                <text class="time-text">{{ orderTicket.ticket.sight.openTime }}</text>
              </view>
              
              <!-- 价格和数量 -->
              <view class="price-quantity">
                <text class="price">¥{{ orderTicket.unitPrice }}</text>
                <text class="quantity">x {{ orderTicket.quantity }}</text>
                <text class="subtotal">小计: ¥{{ (orderTicket.unitPrice * orderTicket.quantity).toFixed(2) }}</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="empty-tickets">
          <text class="empty-text">暂无门票信息</text>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="section order-info-section">
        <view class="section-title">
          <text class="title-text">订单信息</text>
        </view>
        <view class="info-list">
          <view class="info-item">
            <text class="info-label">订单号</text>
            <text class="info-value">{{ orderDetail.orderId }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">创建时间</text>
            <text class="info-value">{{ formatDateTime(orderDetail.createdAt) }}</text>
          </view>
          <view v-if="orderDetail.paymentTime" class="info-item">
            <text class="info-label">支付时间</text>
            <text class="info-value">{{ formatDateTime(orderDetail.paymentTime) }}</text>
          </view>
          <view v-if="orderDetail.paymentMethod" class="info-item">
            <text class="info-label">支付方式</text>
            <text class="info-value">{{ formatPaymentMethod(orderDetail.paymentMethod) }}</text>
          </view>
        </view>
      </view>

      <!-- 价格信息 -->
      <view class="section price-section">
        <view class="price-item">
          <text class="price-label">商品总价</text>
          <text class="price-value">¥{{ orderDetail.totalPrice }}</text>
        </view>
        <view class="price-item total">
          <text class="price-label">实付款</text>
          <text class="price-value highlight">¥{{ orderDetail.totalPrice }}</text>
        </view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="footer-actions">
        <button 
          v-if="orderDetail.status === 'pending'" 
          class="action-btn cancel-btn" 
          @click="cancelOrder"
        >
          取消订单
        </button>
        <button 
          v-if="orderDetail.status === 'pending'" 
          class="action-btn primary-btn" 
          @click="payOrder"
        >
          立即支付
        </button>
        <button 
          v-if="orderDetail.status === 'paid'" 
          class="action-btn primary-btn" 
          @click="useTicket"
        >
          去使用
        </button>
        <button 
          v-if="orderDetail.status === 'paid'" 
          class="action-btn refund-btn" 
          @click="refundOrder"
        >
          申请退款
        </button>
        <button 
          v-if="orderDetail.status === 'comment'" 
          class="action-btn primary-btn" 
          @click="commentOrder"
        >
          去评价
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { orderApi } from '@/common/api/order.js'

// 响应式数据
const loading = ref(false)
const error = ref('')
const orderDetail = ref(null)
const orderId = ref('')

// 页面加载时获取订单ID
onLoad((options) => {
  if (options.id) {
    orderId.value = options.id
    fetchOrderDetail()
  } else {
    error.value = '缺少订单ID'
  }
})

// 获取订单详情
const fetchOrderDetail = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const res = await orderApi.getOrderDetail(orderId.value)
    
    if (res.code === 200 && res.data) {
      orderDetail.value = res.data
    } else {
      error.value = res.message || '获取订单详情失败'
    }
  } catch (err) {
    console.error('获取订单详情失败:', err)
    error.value = '网络错误，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 格式化订单状态
const formatStatus = (status) => {
  const statusMap = {
    'pending': '待支付',
    'paid': '已支付',
    'comment': '待评价',
    'completed': '已完成',
    'canceled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取状态描述
const getStatusDesc = (status) => {
  const descMap = {
    'pending': '请尽快完成支付',
    'paid': '订单已支付成功，请按时使用',
    'comment': '期待您的评价',
    'completed': '感谢您的使用',
    'canceled': '订单已取消',
    'refunded': '退款已完成'
  }
  return descMap[status] || ''
}

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    'pending': '⏱',
    'paid': '✓',
    'comment': '📝',
    'completed': '✓',
    'canceled': '✕',
    'refunded': '↺'
  }
  return iconMap[status] || '•'
}

// 获取状态图标类名
const getStatusIconClass = (status) => {
  return `icon-${status}`
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取景点图片
const getSightImage = (sight) => {
  if (!sight) return '/static/logo.png'
  if (sight.images && Array.isArray(sight.images) && sight.images.length > 0) {
    return sight.images[0]
  }
  return '/static/logo.png'
}

// 获取票类型名称
const getTicketTypeName = (type) => {
  const typeMap = {
    'adult': '成人票',
    'child': '儿童票',
    'student': '学生票',
    'senior': '老人票',
    'group': '团购票'
  }
  return typeMap[type] || type || '门票'
}

// 格式化支付方式
const formatPaymentMethod = (method) => {
  const methodMap = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'balance': '余额支付'
  }
  return methodMap[method] || method || '未知'
}

// 取消订单
const cancelOrder = () => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消该订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await orderApi.cancelOrder(orderId.value)
          if (response.code === 200) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            // 刷新订单详情
            setTimeout(() => {
              fetchOrderDetail()
            }, 1500)
          } else {
            uni.showToast({
              title: response.message || '取消订单失败',
              icon: 'none'
            })
          }
        } catch (err) {
          console.error('取消订单失败:', err)
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 支付订单
const payOrder = () => {
  uni.navigateTo({ 
    url: `/pages/orders/alipay?orderId=${orderId.value}` 
  })
}

// 使用门票
const useTicket = () => {
  uni.navigateTo({ 
    url: `/pages/orders/ticket-detail?orderId=${orderId.value}` 
  })
}

// 申请退款
const refundOrder = () => {
  uni.showModal({
    title: '申请退款',
    content: '确定要申请退款吗？',
    success: (res) => {
      if (res.confirm) {
        // TODO: 实现退款逻辑
        uni.showToast({
          title: '退款功能开发中',
          icon: 'none'
        })
      }
    }
  })
}

// 评价订单
const commentOrder = () => {
  uni.showModal({
    title: '评价订单',
    content: '前往评价页面',
    success: (res) => {
      if (res.confirm) {
        // TODO: 跳转到评价页面
        uni.showToast({
          title: '评价功能开发中',
          icon: 'none'
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
// 使用主题色
$brand-theme-color: #98c3fd;
$primary-text: #333333;
$secondary-text: #666666;
$tertiary-text: #999999;
$background-color: #f8f8f8;
$card-background: #ffffff;
$border-color: #eeeeee;
$success-color: #52c41a;
$warning-color: #faad14;
$danger-color: #ff4d4f;
$info-color: #1890ff;

.order-detail-page {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 120rpx;

  // 加载状态
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;

    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 6rpx solid rgba(152, 195, 253, 0.3);
      border-top-color: $brand-theme-color;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .loading-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: $tertiary-text;
    }
  }

  // 错误状态
  .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;

    .error-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      background-color: rgba(255, 77, 79, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 60rpx;
      color: $danger-color;
      margin-bottom: 20rpx;
    }

    .error-text {
      font-size: 30rpx;
      color: $secondary-text;
      margin-bottom: 40rpx;
    }

    .retry-btn {
      background-color: $brand-theme-color;
      color: white;
      border-radius: 40rpx;
      padding: 0 60rpx;
      font-size: 28rpx;
    }
  }

  // 订单内容
  .order-content {
    // 订单状态卡片
    .status-card {
      background: linear-gradient(135deg, $brand-theme-color 0%, #5a9ef9 100%);
      padding: 40rpx 30rpx;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .status-icon {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 30rpx;

        .icon-text {
          font-size: 50rpx;
        }

        &.icon-pending {
          .icon-text {
            color: $warning-color;
          }
        }

        &.icon-paid,
        &.icon-completed {
          .icon-text {
            color: $success-color;
          }
        }

        &.icon-canceled,
        &.icon-refunded {
          .icon-text {
            color: $tertiary-text;
          }
        }
      }

      .status-info {
        flex: 1;

        .status-text {
          display: block;
          font-size: 40rpx;
          font-weight: 600;
          color: white;
          margin-bottom: 10rpx;
        }

        .status-desc {
          display: block;
          font-size: 26rpx;
          color: rgba(255, 255, 255, 0.9);
        }
      }
    }

    // 通用区块样式
    .section {
      background-color: $card-background;
      margin-bottom: 20rpx;
      padding: 30rpx;

      .section-title {
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid $border-color;
        margin-bottom: 20rpx;

        .title-text {
          font-size: 32rpx;
          font-weight: 600;
          color: $primary-text;
        }
      }
    }

    // 门票列表
    .tickets-section {
      .tickets-list {
        .ticket-card {
          display: flex;
          padding: 20rpx;
          background-color: #fafafa;
          border-radius: 16rpx;
          margin-bottom: 20rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .ticket-image-wrapper {
            width: 200rpx;
            height: 200rpx;
            border-radius: 12rpx;
            overflow: hidden;
            margin-right: 20rpx;
            flex-shrink: 0;

            .ticket-image {
              width: 100%;
              height: 100%;
              display: block;
            }
          }

          .ticket-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .sight-name {
              font-size: 32rpx;
              font-weight: 600;
              color: $primary-text;
              margin-bottom: 8rpx;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
            }

            .ticket-type {
              font-size: 26rpx;
              color: $brand-theme-color;
              margin-bottom: 10rpx;
            }

            .sight-address,
            .open-time {
              display: flex;
              align-items: center;
              font-size: 24rpx;
              color: $tertiary-text;
              margin-bottom: 6rpx;

              .address-text,
              .time-text {
                margin-left: 6rpx;
              }
            }

            .price-quantity {
              display: flex;
              align-items: center;
              margin-top: 10rpx;

              .price {
                font-size: 32rpx;
                font-weight: 600;
                color: $danger-color;
                margin-right: 10rpx;
              }

              .quantity {
                font-size: 26rpx;
                color: $secondary-text;
                margin-right: 20rpx;
              }

              .subtotal {
                font-size: 26rpx;
                color: $secondary-text;
                margin-left: auto;
              }
            }
          }
        }
      }

      .empty-tickets {
        text-align: center;
        padding: 60rpx 0;

        .empty-text {
          font-size: 28rpx;
          color: $tertiary-text;
        }
      }
    }

    // 订单信息列表
    .order-info-section {
      .info-list {
        .info-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20rpx 0;
          border-bottom: 1rpx solid $border-color;

          &:last-child {
            border-bottom: none;
          }

          .info-label {
            font-size: 28rpx;
            color: $secondary-text;
          }

          .info-value {
            font-size: 28rpx;
            color: $primary-text;
            text-align: right;
            flex: 1;
            margin-left: 20rpx;
          }
        }
      }
    }

    // 价格区块
    .price-section {
      .price-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15rpx 0;

        .price-label {
          font-size: 28rpx;
          color: $secondary-text;
        }

        .price-value {
          font-size: 28rpx;
          color: $primary-text;

          &.highlight {
            font-size: 36rpx;
            font-weight: 600;
            color: $danger-color;
          }
        }

        &.total {
          padding-top: 20rpx;
          border-top: 1rpx solid $border-color;
          margin-top: 10rpx;
        }
      }
    }

    // 底部操作按钮
    .footer-actions {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: $card-background;
      padding: 20rpx 30rpx;
      box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
      display: flex;
      gap: 20rpx;
      z-index: 100;

      .action-btn {
        flex: 1;
        height: 80rpx;
        border-radius: 40rpx;
        font-size: 30rpx;
        line-height: 80rpx;
        padding: 0;

        &.primary-btn {
          background: linear-gradient(135deg, $brand-theme-color 0%, #5a9ef9 100%);
          color: white;
          border: none;
        }

        &.cancel-btn {
          background-color: white;
          color: $secondary-text;
          border: 1rpx solid $border-color;
        }

        &.refund-btn {
          background-color: white;
          color: $warning-color;
          border: 1rpx solid $warning-color;
        }
      }
    }
  }
}

// 动画
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>

